package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约ServiceImpl
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    public void saveOrder(Order order) {
        orderDao.save(order);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate());
        Integer number = orderSettingDao.getReservationsByDate(format);
        orderSettingDao.updateReservations(--number, format);
    }

    @Override
    public Order getOrderByToday(Integer id, String date) {
        return orderDao.getOrderByToday(id, date);
    }

    @Override
    public boolean isCanReserve(String orderDate) {
        boolean flag = true;
        OrderSetting orderSetting = orderSettingDao.getOrderSettingByDate(orderDate);
        int reservations = orderSetting.getReservations();
        if (reservations == 0) {
            return !flag;
        }
        return flag;
    }

    /* 判断该用户该日是否预约过此套餐 */
    @Override
    public Order findSetmealByDate(Integer id, Date date, Integer setmealId) {
        return orderDao.findSetmealByDate(id, date, setmealId);
    }

    /* 添加订单 */
    @Override
    public void addOrder(Order order) {
        orderDao.addOrder(order);
        Date date = order.getOrderDate();
        Integer newNumber = orderSettingDao.
                findRereservationsByDate(date) - 1;
        orderSettingDao.updateOrderSetting(date, newNumber);

    }

    @Override
    public Map<String, Object> findById(Integer id) {
        Map<String, Object> data = orderDao.selectDetailById(id);
        String orderDate = data.get("orderDate").toString();
        data.put("orderDate", orderDate);
        return data;
    }
}
